<template>
  <div class="row">
    <div class="col-12 text-subtitle1 text-center">重置密码</div>
    <div class="col-12 text-subtitle2 text-center" v-if="subTitle">
      {{ subTitle }}
    </div>
    <q-banner inline-actions rounded class="col-12 text-white bg-red q-mt-sm" v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn flat icon="close" size="sm" dense @click="serverErrorMessage = null" />
      </template>
    </q-banner>

    <q-input class="col-12 q-mt-md" v-model="form.newPassword" placeholder="新密码" type="password" outlined square dense
      autofocus :disable="workingState" :error="v$.newPassword.$error" :error-message="e$(v$.newPassword.$errors)" no-error-icon
      :hide-bottom-space="true">
      <template v-slot:append>
        <q-icon color="primary" name="vpn_key" />
      </template>
    </q-input>

    <q-input class="col-12 q-mt-md" v-model="form.repeatNewPassword" placeholder="再次确认新密码" type="password" outlined square
      dense :disable="workingState" :error="v$.repeatNewPassword.$error" :error-message="e$(v$.repeatNewPassword.$errors)" no-error-icon
      :hide-bottom-space="true">
      <template v-slot:append>
        <q-icon color="primary" name="vpn_key" />
      </template>
    </q-input>

    <q-btn class="q-mt-md col-12" color="primary" label="确定" :loading="workingState" @click="confirm">
      <template v-slot:loading>
        <q-spinner class="on-left" />提交中...
      </template>
    </q-btn>
  </div>
</template>

<script lang="ts">
export default {
  name: 'resetPasswordStd'
}
</script>

<script lang="ts" setup>
import { reactive, ref, computed, onBeforeMount } from 'vue'
import useVuelidate from '@vuelidate/core'
import {useJsencryptHelper} from '../../hooks/jsencryptHelper'

const serverErrorMessage = ref('')
const workingState = ref(false)
const e$ = $f.getFieldErrStr

const subTitle = ref('') //目前可能是这两个：密码过期需要修改密码 / 首次登录需要修改密码
const pageMode = ref('3') //'1'表示初次登录需要修改密码 '2'表示密码过期需要修改密码 '3'表示找回密码重置
const reurl = ref('') //返回路径

//属性
const props = defineProps({
  useStrictPassword: {
    type: Boolean,
    default: false
  },
  useExtraPasswordCheck:{
    type: Boolean,
    default: false,
  }
})

//表单
const form = reactive({
  newPassword: '',
  repeatNewPassword: ''
})

//表单验证
const rules = {
  newPassword: {
    required: $f.validators.required,
    password: props.useStrictPassword ? $f.validators.strictPassword: $f.validators.password,
    extraPasswordRepeatCheck:(props.useStrictPassword && props.useExtraPasswordCheck)?$f.validators.extraPasswordRepeatCheck:''
  },
  repeatNewPassword: {
    required: $f.validators.required,
    password: props.useStrictPassword ? $f.validators.strictPassword : $f.validators.password,
    passwordConfirm: $f.validators.passwordConfirm(computed(() => form.newPassword)),
    extraPasswordRepeatCheck:(props.useStrictPassword && props.useExtraPasswordCheck)?$f.validators.extraPasswordRepeatCheck:''
  }
}

//用于提交的表单
const formToSubmit = {
  username: '',
  password: '',
  opToken: ''
}

const v$ = useVuelidate(rules, form, { $autoDirty: true })

onBeforeMount(() => {
  // URL参数
  const query = $f.router.currentRoute.value.query
  const optoken = query.optoken as string
  const username = query.username as string
  const type = query.type as string
  const title = query.title as string
  const returnUrl = query.reurl as string

  if (
    optoken &&
    username &&
    type &&
    $f.regex.regGuid.test(optoken) &&
    $f.valFuncs.isValidUserName(username) &&
    /^[123]$/.test(type)
  ) {
    subTitle.value = title
    reurl.value = returnUrl
    pageMode.value = type
    if (!reurl.value) {
      reurl.value = '/'
    }
    formToSubmit.opToken = optoken
    formToSubmit.username = username
  } else {
    $f.errorState.value = 1
  }
})

const serverUrl = computed(() => {
  switch (pageMode.value) {
    case '1':
      return 'comm/auth/set-password-first-time'
    case '2':
      return 'comm/auth/renew-password'
    default:
      // must be '3'
      return 'comm/auth/reset-password'
  }
})
const encPassword = useJsencryptHelper()

const confirm = function () {
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        formToSubmit.password = form.newPassword
        workingState.value = true
        serverErrorMessage.value = ''
        let model
        if($f.globalCfg.encTransPwd){
          model = {
            username: formToSubmit.username,
            opToken: formToSubmit.opToken,
            useEncryptPwd: true,
            encryptedPwd: encPassword(formToSubmit.password),
          }
        }
        else{
          model = formToSubmit
        }
        $f.axios
          .post(serverUrl.value, model)
          .then(() => {
            void $f.router.push('/comm/auth/login?reurl=' + encodeURIComponent(reurl.value))
          })
          .catch((err) => {
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
            workingState.value = false
          })
      }
    })
}
</script>
